<?php
/**
 * Created by PhpStorm.
 * User: Lyq
 * Date: 2018/8/22
 * Time: 上午8:21
 */

namespace app\admin\controller;

use think\Exception;
use think\Db;
use app\common\model\Message;

class Goods extends Common
{
    //商品列表
    public function index()
    {
        $this->templateTitle('商品列表');

        //判断条件
        $where = [];

        $id = trim(request()->param('id'));
        $this->assign('id', $id);
        if (!empty($id)) {
            $where['g.id'] = intval($id);
        }

        //商品标题
        $title = request()->param("title");
        $this->assign("title", $title);
        if ($title) {
            $where["g.title"] = ["LIKE", "%$title%"];
        }

        //所属分类
        $category_id1 = trim(request()->param('category_id1'));
        $this->assign('category_id1', $category_id1);
        if ($category_id1) {
            $where['g.category_id1'] = intval($category_id1);
        }

        //所属分类
        $category_id2 = trim(request()->param('category_id2'));
        $this->assign('category_id2', $category_id2);
        if ($category_id2) {
            $where['g.category_id2'] = intval($category_id2);
        }

//        //所属分类
//        $category_id3 = trim(request()->param('category_id3'));
//        $this->assign('category_id3', $category_id3);
//        if ($category_id3) {
//            $where['g.category_id3'] = intval($category_id3);
//        }

        //是否上下架
        $status = trim(request()->param('status'));
        $this->assign('status', $status);
        if ($status != '') {
            $where['g.status'] = intval($status);
        }
        //是否预售
        $is_presell = trim(request()->param('is_presell'));
        $this->assign('is_presell', $is_presell);
        if ($is_presell != '') {
            $where['g.is_presell'] = intval($is_presell);
        }
        //商品品牌
        $brand_id = trim(request()->param('brand_id'));
        $this->assign('brand_id', $brand_id);
        if($brand_id>0){
            $where["brand_id"] = $brand_id;
        }
        //获取商品列表
        $list = Db::name("goods")
            ->alias('g')
            ->join('__CATEGORY__ c1', 'c1.id=g.category_id1', 'LEFT')
            ->join('__CATEGORY__ c2', 'c2.id=g.category_id2', 'LEFT')
//            ->join('__CATEGORY__ c3', 'c3.id=g.category_id3', 'LEFT')
            ->where($where)
            ->field('g.*,c1.title as c1_title,c1.is_visible as c1_visible,c2.title as c2_title,c2.is_visible as c2_visible')
//            ->field('g.*,c1.title as c1_title,c1.is_visible as c1_visible,c2.title as c2_title,c2.is_visible as c2_visible,c3.title as c3_title,c3.is_visible as c3_visible')
            ->order("g.display_order DESC,g.id DESC")
            ->paginate(10);
        $this->assign("list", $list);
        //加载所有品牌
        $brand = \db('brand')->where("is_valid", 1)->column("title", "id");
        $this->assign("brand", $brand);
        //加载所有预售区
        $presell = \db('presell')->column("title", "id");
        $this->assign("presell", $presell);
        return $this->fetch();
    }

    //更改
    public function status()
    {
        if (request()->isAjax()) {
            //菜单ID
            $id = request()->param("id");
            //获取可见性状态
            $status = request()->param("status");
            try {
                //修改菜单显示隐藏
                $save = Db::name("goods")
                    ->where("id", $id)
                    ->setField("status", $status);

                if ($save) {
                    /*操作记录*/
                    Message::admin_log(0, "后台改变商品状态");
                    return $this->ajaxSuccess("设置商品状态成功！");
                } else {
                    return $this->ajaxError("设置商品状态失败！");
                }
            } catch (Exception $exception) {
                return $this->ajaxError($exception->getMessage());
            }
        }
    }
    //更改首页推荐
    public function isIndex()
    {
        if (request()->isAjax()) {
            //菜单ID
            $id = request()->param("id");
            //获取可见性状态
            $status = request()->param("status");
            try {
                //修改菜单显示隐藏
                $save = Db::name("goods")
                    ->where("id", $id)
                    ->setField("is_index", $status);
                if ($save) {
                    /*操作记录*/
                    Message::admin_log(0, "后台改变商品首推状态");
                    return $this->ajaxSuccess("设置成功！");
                } else {
                    return $this->ajaxError("设置失败！");
                }
            } catch (Exception $exception) {
                return $this->ajaxError($exception->getMessage());
            }
        }
    }

    //添加商品
    public function add()
    {
        $dispatch_type = get_dispatch_type();
        if (request()->isGet()) {
            $this->layoutModal();
            $this->assign("range_start", ["time_range" => date("Y-m-d")]);
            $this->assign("range_end", ["time_range" => date("Y-m-d H:i")]);
            $this->assign("range_start2", ["time_rangeone" => date("Y-m-d H:i")]);
            $this->assign('dispatch_type', $dispatch_type);
            //获取商品列表
            $goodModel = new \app\common\model\Goods();
            $good_list=$goodModel->field("id, title")->select();
            $this->assign("good_list", $good_list);
            //获取预售模块
            $presell = \db("presell")->field("id, title")->select();
            $this->assign("pre_sell", $presell);
            return $this->fetch();
        }

        if (request()->isAjax()) {
            //创建数据
            $data = array(
                "create_time" => now_datetime(),
                "update_time" => now_datetime(),
            );
            //一二三分类
            $data['category_id1'] = intval(request()->param('category_id1'));
            $data['category_id2'] = intval(request()->param('category_id2'));
//            $data['category_id3'] = intval(request()->param('category_id3'));
            if (empty($data['category_id1']) || empty($data['category_id2'])) {
                return $this->ajaxError('选择分类不完整');
            }
            //品牌
            $data['brand_id'] = intval(request()->param('brand_id'));
            if(empty($data["brand_id"])){
                return $this->ajaxError('品牌未选择');
            }

            //商品标题
            $data["title"] = trim(request()->param("title"));
            if (empty($data['title'])) {
                return $this->ajaxError('请输入商品标题');
            }

            //商品短标题
            $data["short_title"] = trim(request()->param("short_title"));
            if (empty($data['short_title'])) {
                return $this->ajaxError('请输入商品短标题');
            }
            //关键字
            $data['keyword'] = trim(request()->param('keyword'));

            //商品缩略图
            $data["img_url"] = trim(request()->param("img_url"));
            if (empty($data['img_url'])) {
                return $this->ajaxError('请上传商品缩略图');
            }
            //默认售价
            $data['price'] = round(request()->param('price'), 2);
            if ($data['price'] < 0.01) {
                return $this->ajaxError('请正确输入默认售价');
            }
            //默认原价
            $data['original_price'] = round(request()->param('original_price'), 2);
            if ($data['original_price'] < 0.01) {
                return $this->ajaxError('请正确输入默认原价');
            }

            $data['dispatch_type'] = intval(request()->param('dispatch_type'));
            if (empty($data['dispatch_type'])) {
                return $this->ajaxError('请选择运费计算模式');
            }

            //运费
            $data['dispatch_price'] = round(request()->param('dispatch_price'), 2);
            //平台排序
            $data['display_order'] = intval(request()->param('display_order'));
            //上架
            $data['status'] = intval(request()->param('status'));
            //是否是预售
            $data['is_presell'] = intval(request()->param('is_presell'));
            if($data["is_presell"] == 1){
                if(input("presell_id")>0){
                    $data["presell_id"] =input("presell_id");
                }else{
                    return $this->ajaxError("请选择预售模块");
                }
            }
            //首页推荐
            $data['is_index'] = intval(request()->param('is_index'));
            //规格
            $data['use_spec'] = intval(request()->param('use_spec'));
            //规格标题
            $data['spec_name'] = trim(request()->param('spec_name'));
            if ($data['use_spec'] == 1) {
                //启用
                $data['stock'] = 0;
                if (empty($data['spec_name'])) {
                    return $this->ajaxError('已启用规格，请输入规格标题');
                }
                if (!isset($_POST['spec'])) {
                    return $this->ajaxError('已启用规格，请上传规格');
                }
                $spec = $_POST['spec'];
                if (!is_array($spec)) {
                    return $this->ajaxError('规格格式有误');
                }

                $spec_data = [];

                foreach ($spec as $keys => $item) {

                    $spec_data[$keys]['title'] = trim($item['title']);
                    $spec_data[$keys]['img_url'] = trim($item['img_url']);
                    $spec_data[$keys]['price'] = round($item['price'], 2);
                    $spec_data[$keys]['original_price'] = round($item['original_price'], 2);
                    $spec_data[$keys]['stock'] = intval($item['stock']);
                    if (empty($spec_data[$keys]['title'])) {
                        return $this->ajaxError('规格中有规格名称为空');
                    }
                    if (empty($spec_data[$keys]['img_url'])) {
                        return $this->ajaxError('规格中有图片未上传');
                    }
                    if ($spec_data[$keys]['price'] < 0.01) {
                        return $this->ajaxError('规格中有售价有误');
                    }
                    if ($spec_data[$keys]['original_price'] < 0.01) {
                        return $this->ajaxError('规格中有原价有误');
                    }
                    $data['stock'] += $spec_data[$keys]['stock'];
                }

            } else {
                //默认库存
                $data['stock'] = intval(request()->param('stock'));
                $spec_data = false;
            }

            //单次最多购买
            $data['maxbuy'] = trim(request()->param('maxbuy'));
            //单次最少购买
            $data['minbuy'] = trim(request()->param('minbuy'));
            //最多购买
            $data['allbuy'] = trim(request()->param('allbuy'));
            //相关商品
            $relative_good = input("relative_id/a");
            //热门推荐
            $recommend_good = input("recommend_id/a");
            try {

                $da['detail'] = request()->param('article_detail');
                $detail_id = Db::name('goods_detail')->insertGetId($da);
                $data['detail_id'] = $detail_id;
                $goods_id = Db::name("goods")->insertGetId($data);
                if (is_array($spec_data)) {
                    foreach ($spec_data as $key => $item) {
                        $spec_data[$key]['goods_id'] = $goods_id;
                    }
                    Db::name('goods_spec')->insertAll($spec_data);
                }
                if (isset($_POST['imglist']) && is_array($_POST['imglist'])) {
                    $img_data = [];
                    foreach ($_POST['imglist'] as $key => $item) {
                        $img_data[$key]['img_url'] = $item;
                        $img_data[$key]['goods_id'] = $goods_id;
                    }
                    Db::name('goods_img')->insertAll($img_data);
                }

                if(is_array($relative_good)){
                    $insert_data = [];
                    foreach ($relative_good as $r){
                        $insert_data[] = [
                            "good_id"=>$goods_id,
                            "relative_id"=>$r
                        ];
                    }
                    \db('good_relative')->insertAll($insert_data);
                }
                if(is_array($recommend_good)){
                    $insert_data = [];
                    foreach ($recommend_good as $r){
                        $insert_data[] = [
                            "good_id"=>$goods_id,
                            "relative_id"=>$r
                        ];
                    }
                    \db('good_recommend')->insertAll($insert_data);
                }
                return $this->ajaxSuccess('添加商品成功');
            } catch (Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                return $this->ajaxError($exception->getMessage());
            }
        }
    }

    //删除规格
    public function removeSpec()
    {
        if (request()->isAjax()) {
            $spec_id = intval(request()->param('spec_id'));
            $goods_id = intval(request()->param('goods_id'));
            $del = Db::name('goods_spec')
                ->where('id', $spec_id)
                ->where('goods_id', $goods_id)
                ->delete();
            if ($del) {
                return $this->ajaxSuccess('此规格删除成功');
            } else {
                return $this->ajaxError('此规格删除失败');
            }
        }
    }

    //编辑商品
    public function edit()
    {
        //商品id
        $id = intval(request()->param('id'));
        $info = Db::name('goods')->where('id', $id)->find();
        $dispatch_type = get_dispatch_type();
        if (request()->isGet()) {
            $this->layoutModal();
            $this->assign('info', $info);
            //处理缩略图
            $this->assign("single_image", array("img_url" => $info["img_url"]));
            //规格
            $spec_list = Db::name('goods_spec')->where('goods_id', $id)->select();
            $this->assign('spec_list', $spec_list);
            //商品附图
            $img_list = Db::name('goods_img')->where('goods_id', $id)->field('img_url')->select();
            $img_list = array_column($img_list, 'img_url');
            $this->assign('multi_image', ['imglist' => $img_list]);
            //商品详情
            $detail = Db::name('goods_detail')->where('id', $info['detail_id'])->value('detail');
            $this->assign("ueditor_content", array("article_detail" => $detail));
            $this->assign('dispatch_type', $dispatch_type);
            //获取相关推荐
            $relative_list = \db("good_relative")->alias("a")->join("goods b", "a.relative_id=b.id")->where("a.good_id", $id)->field('a.relative_id id, b.title')->select();
            $this->assign("rel_list", $relative_list);
            //获取热门推荐
            $recommend_list = \db("good_recommend")->alias("a")->join("goods b", "a.relative_id=b.id")->where("a.good_id", $id)->field('a.relative_id id, b.title')->select();
            $this->assign("rec_list", $recommend_list);


            //获取预售模块
            $presell = \db("presell")->field("id, title")->select();
            $this->assign("pre_sell", $presell);
            //获取商品列表
            $goodModel = new \app\common\model\Goods();
            $good_list=$goodModel->where("id", "neq", $id)->field("id, title")->select();
            $this->assign("good_list", $good_list);
            return $this->fetch();
        }

        if (request()->isAjax()) {
            //创建数据
            $data = array(
                "update_time" => now_datetime(),
            );
            //一二三分类
            $data['category_id1'] = intval(request()->param('category_id1'));
            $data['category_id2'] = intval(request()->param('category_id2'));
//            $data['category_id3'] = intval(request()->param('category_id3'));
            if (empty($data['category_id1']) || empty($data['category_id2'])) {
                return $this->ajaxError('选择分类不完整');
            }
            //品牌
            $data['brand_id'] = intval(request()->param('brand_id'));
            if(empty($data["brand_id"])){
                return $this->ajaxError('品牌未选择');
            }
            //商品标题
            $data["title"] = trim(request()->param("title"));
            if (empty($data['title'])) {
                return $this->ajaxError('请输入商品标题');
            }

            //商品短标题
            $data["short_title"] = trim(request()->param("short_title"));
            if (empty($data['short_title'])) {
                return $this->ajaxError('请输入商品短标题');
            }
            //关键字
            $data['keyword'] = trim(request()->param('keyword'));

            //商品缩略图
            $data["img_url"] = trim(request()->param("img_url"));
            if (empty($data['img_url'])) {
                return $this->ajaxError('请上传商品缩略图');
            }
            //默认售价
            $data['price'] = round(request()->param('price'), 2);
            if ($data['price'] < 0.01) {
                return $this->ajaxError('请正确输入默认售价');
            }
            //默认原价
            $data['original_price'] = round(request()->param('original_price'), 2);
            if ($data['original_price'] < 0.01) {
                return $this->ajaxError('请正确输入默认原价');
            }

            $data['dispatch_type'] = intval(request()->param('dispatch_type'));
            if (empty($data['dispatch_type'])) {
                return $this->ajaxError('请选择运费计算模式');
            }

            //运费
            $data['dispatch_price'] = round(request()->param('dispatch_price'), 2);
            //平台排序
            $data['display_order'] = intval(request()->param('display_order'));
            //上架
            $data['status'] = intval(request()->param('status'));
            //是否预售
            $data['is_presell'] = intval(request()->param('is_presell'));
            if($data["is_presell"] == 1){
                if(input("presell_id")>0){
                    $data["presell_id"] =input("presell_id");
                }else{
                    return $this->ajaxError("请选择预售模块");
                }
            }
            //首页推荐
            $data['is_index'] = intval(request()->param('is_index'));
            //规格
            $data['use_spec'] = intval(request()->param('use_spec'));
            //规格标题
            $data['spec_name'] = trim(request()->param('spec_name'));
            if ($data['use_spec'] == 1) {
                //启用
                $data['stock'] = 0;
                if (empty($data['spec_name'])) {
                    return $this->ajaxError('已启用规格，请输入规格标题');
                }
                if (!isset($_POST['spec'])) {
                    return $this->ajaxError('已启用规格，请上传规格');
                }
                $spec = $_POST['spec'];
                if (!is_array($spec)) {
                    return $this->ajaxError('规格格式有误');
                }

                $spec_data = [];

                foreach ($spec as $keys => $item) {
                    $spec_data[$keys]['id'] = intval($item['id']);
                    $spec_data[$keys]['title'] = trim($item['title']);
                    $spec_data[$keys]['img_url'] = trim($item['img_url']);
                    $spec_data[$keys]['price'] = round($item['price'], 2);
                    $spec_data[$keys]['original_price'] = round($item['original_price'], 2);
                    $spec_data[$keys]['stock'] = intval($item['stock']);
                    if (empty($spec_data[$keys]['title'])) {
                        return $this->ajaxError('规格中有规格名称为空');
                    }
                    if (empty($spec_data[$keys]['img_url'])) {
                        return $this->ajaxError('规格中有图片未上传');
                    }
                    $data['stock'] += $spec_data[$keys]['stock'];
                }

            } else {
                //默认库存
                $data['stock'] = intval(request()->param('stock'));
                $spec_data = false;
            }

            //单次最多购买
            $data['maxbuy'] = trim(request()->param('maxbuy'));
            //单次最少购买
            $data['minbuy'] = trim(request()->param('minbuy'));
            //最多购买
            $data['allbuy'] = trim(request()->param('allbuy'));

            try {
                Db::name("goods")->where('id', $id)->update($data);
                if (is_array($spec_data)) {
                    foreach ($spec_data as $key => $item) {
                        if (!empty($spec_data[$key]['id'])) {
                            $spec_id = $spec_data[$key]['id'];
                            unset($spec_data[$key]['id']);
                            Db::name('goods_spec')->where('id', $spec_id)->update($spec_data[$key]);
                            unset($spec_data[$key]);
                        } else {
                            unset($spec_data[$key]['id']);
                            $spec_data[$key]['goods_id'] = $id;
                        }
                    }
                    if (count($spec_data) > 0) {
                        Db::name('goods_spec')->insertAll($spec_data);
                    }
                }
                Db::name('goods_img')->where('goods_id', $id)->delete();
                if (isset($_POST['imglist']) && is_array($_POST['imglist'])) {
                    $img_data = [];
                    foreach ($_POST['imglist'] as $key => $item) {
                        $img_data[$key]['img_url'] = $item;
                        $img_data[$key]['goods_id'] = $id;
                    }
                    Db::name('goods_img')->insertAll($img_data);
                }
                $da['detail'] = request()->param('article_detail');
                Db::name('goods_detail')->where('id', $info['detail_id'])->update($da);
                //加载相关产品
                $relative_good = input("relative_id/a");
                \db("good_relative")->where("good_id", $id)->delete();
                if(is_array($relative_good)){
                    $insert_data = [];
                    foreach ($relative_good as $r){
                        $insert_data[] = [
                            "good_id"=>$id,
                            "relative_id"=>$r
                        ];
                    }
                    \db('good_relative')->insertAll($insert_data);
                }
                //加载热门推荐产品
                $recommend_good = input("recommend_id/a");
                \db("good_recommend")->where("good_id", $id)->delete();
                if(is_array($recommend_good)){
                    $insert_data = [];
                    foreach ($recommend_good as $r){
                        $insert_data[] = [
                            "good_id"=>$id,
                            "relative_id"=>$r
                        ];
                    }
                    \db('good_recommend')->insertAll($insert_data);
                }
                /*操作记录*/
                Message::admin_log(0, "后台修改商品");
                return $this->ajaxSuccess('编辑商品成功');
            } catch (Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                return $this->ajaxError($exception->getMessage());
            }
        }
    }

    //删除商品
    public function remove()
    {
        if (request()->isAjax()) {
            //商品ID
            $id = request()->param("id");
            try {
                $check = Db::name('order_goods')
                    ->alias('og')
                    ->join('__ORDER__ o', 'o.order_sn=og.order_sn AND o.pay_status=1 and o.order_status=1')
                    ->where('og.goods_id', $id)
                    ->find();
                if ($check) {
                    $this->ajaxError('此商品还有未发货的订单，暂时无法删除');
                }

                $old = Db::name("goods")
                    ->where("id", $id)
                    ->find();

                //更新商品
                $del = Db::name("goods")
                    ->where("id", $id)
                    ->delete();

                if ($del) {
                    /*操作记录*/
                    Message::admin_log(0, "后台删除商品");
                    //附表
                    Db::name('goods_car')->where('goods_id', $id)->delete();
                    Db::name('goods_comment')->where('goods_id', $id)->delete();
                    Db::name('goods_detail')->where('id', $old['detail_id'])->delete();
                    Db::name('goods_img')->where('goods_id', $id)->delete();
                    Db::name('goods_spec')->where('goods_id', $id)->delete();
                    //清除缓存
                    clear_cache();
                    $this->ajaxSuccess('商品删除成功');
                } else {
                    $this->ajaxError('商品删除失败');
                }
            } catch (Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    /**
     * 预售专区
     */
    public function presell()
    {

        $this->templateTitle("预售管理");
        $list = \db("presell")->paginate(10);
        $this->assign("page", $list->render());
        $this->assign("list", $list);
        return $this->fetch("presell");
    }
    /*
     * 添加预售
     */
    public function addPresell()
    {

        $this->layoutModal();
        if(request()->isAjax()){
            $data = input("post.");
            $data["end_time"] = strtotime($data["end_time"]);
            $res = \db("presell")->insert($data);
            if($res){
                $this->ajaxSuccess("添加成功");
            }else{
                $this->ajaxError("添加失败");
            }
        }
        $this->assign("range_start2", ['end_time'=>date("Y-m-d")]);
        return $this->fetch("addpresell");
        
    }
    /*
     * 编辑预售
     */
    public function editPresell()
    {

        $this->layoutModal();
        $presell_id = input("id");
        if(request()->isAjax()){
            $data = input("post.");
            $data["end_time"] = strtotime($data["end_time"]);
            $res = \db("presell")->where("id", $presell_id)->update($data);
            if($res){
                $this->ajaxSuccess("编辑成功");
            }else{
                $this->ajaxError("编辑失败");
            }
        }
        $info = \db("presell")->where("id", $presell_id)->find();
        $this->assign("range_start2", ['end_time'=>date("Y-m-d H:i:s", $info['end_time'])]);
        $this->assign("single_image", array("img_url" => $info["img_url"]));
        $this->assign("info", $info);
        return $this->fetch("editpresell");
    }

    /**
     * 删除预售
     */
    public function delPresell()
    {
        $presell_id = input("id");
        \db("goods")->where("presell_id", $presell_id)->update([
            "is_presell"=>0,
            "presell_id"=>0
        ]);
        \db("presell")->where("id", $presell_id)->delete();
        $this->ajaxSuccess("删除成功");
    }
    
    
}